import store from '@/store'

export default {
  inserted(el, binding, vnode) {
    const {value} = binding
    const roles = store.getters && store.getters.roles
    const authCodes = store.getters && store.getters.authCodes
    if (value && value instanceof Array && value.length > 0) {
      const permissionRoles = value
      //角色过滤，如admin
      var hasPermission = roles.some(role => {
        return permissionRoles.includes(role)
      })

      if (!hasPermission) {
        //菜单资源过滤
        hasPermission = authCodes.some(authCode => {
          return permissionRoles.includes(authCode)
        })
      }

      if (!hasPermission) {
        el.parentNode && el.parentNode.removeChild(el)
      }
    } else if (value) {
      throw new Error(`使用方式： v-permission="['admin','editor']"`)
    } else {
      el.parentNode && el.parentNode.removeChild(el)
    }
  }
}
